<?php
class SleekCMS_LoginModule extends Module {
	public function run () {
		# Handle logouts
		if (isset($_GET['logout'])) {
			User()->logout();
			redirect('?logged_out'); # url(HOME_PAGE)
		}

		# Create login form
		$form = new Form('login', '', 'post', t('Sign in'), array_merge(User()->asArray(), $_POST));

		$form->addField(array(
			'name'			=> 'email', 
			'type'			=> 'email', 
			'title'			=> t('E-mail'), 
			'placeholder'	=> t('Your e-mail address'), 
			'autofocus'		=> true, 
			'required'		=> true
		));
		$form->addField(array(
			'name'			=> 'password', 
			'type'			=> 'password', 
			'title'			=> t('Password'), 
			'placeholder'	=> t('Your password'), 
			'required'		=> true
		));
	/*	$form->addField(array(
			'name'			=> 'remember', 
			'type'			=> 'checkbox', 
			'title'			=> t('Stay signed in')
		)); */

		if ($data = $form->isSubmitted()) {
			if ($form->validate()) {
				if (User()->login($data['email'], $data['password'])) {
					redirect('?logged_in'); # url(HOME_PAGE)
				}
				else {
					$form->setError(t('Wrong username or password.'));
				}
			}
			else {
				$form->setError(t('Make sure you fill out all the fields properly.'));
			}
		}

		$this->setData('form', $form->asHTML());
	}
}
